﻿using Easy.Services.DbContexts;
using Easy.Services.Dtos;
using Easy.Services.Entities;
using Easy.Services.Interface;
using System.Linq.Expressions;

namespace Easy.Services.Core
{
    internal class IOSService : IIOSService
    {

        public long Add(IOS model)
        {
            using MySQLDbContext db = new();
            BaseService<IOS> baseService = new(db);
            return baseService.AddBase(model);

        }

        public List<IOS> GetList(Expression<Func<IOS, bool>> expression = null)
        {
            using MySQLDbContext db = new();
            BaseService<IOS> baseService = new(db);
            return baseService.GetList(expression);

        }

        public IOSStatisticsDTO GetStatistics(Expression<Func<IOS, bool>> expression = null)
        {
            IOSStatisticsDTO dto = new();
            DateTime time = DateTime.Now;
            DateTime startTime = DateTime.Now.AddMonths(-1).Date;
            var queryData = this.GetList(i => i.CreaterDate > startTime);
            var queryCpuGroup = queryData.GroupBy(q => q.CreaterDate.Value.ToString("yyyy-MM-dd"));
            List<string> xAxisData = [];
            List<string> seriesMaxCPUData = [];
            List<string> seriesMinCPUData = [];
            List<string> seriesRAMData = [];
            List<string> seriesStorageData = [];
            foreach (var item in queryCpuGroup)
            {
                xAxisData.Add(item.Key);
                var maxCpu = item.Sum(i => Convert.ToDouble(i.MaxCPU)) / item.Count();
                var minCpu = item.Sum(i => Convert.ToDouble(i.MinCPU)) / item.Count();
                var ram = item.Sum(i => Convert.ToDouble(i.RAM)) / item.Count();
                var storage = item.Sum(i => Convert.ToDouble(i.Storage)) / item.Count();
                seriesMaxCPUData.Add(maxCpu.ToString("F2"));
                seriesMinCPUData.Add(minCpu.ToString("F2"));
                seriesRAMData.Add(ram.ToString("F2"));
                seriesStorageData.Add(storage.ToString("F2"));
            }
            dto.SeriesMaxCPUData = [.. seriesMaxCPUData];
            dto.SeriesMinCPUData = [.. seriesMinCPUData];
            dto.SeriesRAMData = [.. seriesRAMData];
            dto.SeriesStorageData = [.. seriesStorageData];
            dto.XAxisCPUData = [.. xAxisData];
            dto.XAxisRAMData = [.. xAxisData];
            dto.XAxisStorageData = [.. xAxisData];
            return dto;
        }


    }
}
